//
//  HomeViewController.m
//  QuickCure
//
//  Created by haoge on 16/9/10.
//  Copyright © 2016年 haoge. All rights reserved.
//

#import "HomeViewController.h"
#import "DiseaseTypeView.h"
#import "ViewController.h"
#import "MyWeatherView.h"
#import "NetWorkTool.h"
#import <CoreLocation/CoreLocation.h>
#import <MapKit/MapKit.h>

#define screenW [UIScreen mainScreen].bounds.size.width

#define screenH [UIScreen mainScreen].bounds.size.height

static NSString *reuseID = @"reuseID";


@interface HomeViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,CLLocationManagerDelegate>

@property(nonatomic,strong)MyWeatherView *myWeatherView;

@property(nonatomic,strong)UICollectionView *myLooper;

@property(nonatomic,strong)NSArray *cellImageArray;

@property(nonatomic,strong)NSTimer *myTimer;

@property(nonatomic,strong)UIPageControl *myPageControl;

@property(nonatomic,strong)CLLocationManager *myLocationManager;

@property(nonatomic,strong)CLGeocoder *myGeocoder;

@property(nonatomic,assign)CLLocationCoordinate2D coordinate;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupUI];
    
    [self addMyWeather];
    
    [self addMyLooper];
    
    //添加疾病类型的视图View
    [self addDiseaseTypeView];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{

        [self startTimer];
    });

    self.myGeocoder = [[CLGeocoder alloc]init];
    
    
    _myLocationManager = [[CLLocationManager alloc]init];
    
    _myLocationManager.delegate = self;
    
    _myLocationManager.desiredAccuracy = kCLLocationAccuracyBest;
    
    
    if (![CLLocationManager locationServicesEnabled]) {
        
        NSLog(@"定位服务为打开,请设置打开");
        return;
    }
    
    if ([self.myLocationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
        
        [self.myLocationManager requestWhenInUseAuthorization];
    }
    
    if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined) {
        
        [self.myLocationManager requestWhenInUseAuthorization];
    }else if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse){
        
        CLLocationDistance distance = 10.0;
        
        self.myLocationManager.distanceFilter = distance;
        
        [self.myLocationManager startUpdatingLocation];
        
    }

}

//- (void)setCoordinate:(CLLocationCoordinate2D)coordinate{
//    
//    _coordinate = coordinate;
//    
//    [self getAddressByLatitude:coordinate.longitude longitude:coordinate.latitude];
//    
//}



- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    CLLocation *location = [locations firstObject];
    
     self.coordinate = location.coordinate;
    
     NSLog(@"经度:%f 维度:%f",self.coordinate.longitude,self.coordinate.latitude);
    
    [self.myGeocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        
        NSLog(@"placemarks %@",placemarks);
        
        NSLog(@"error %@",error);
        
        for(CLPlacemark *placemark in placemarks){
            
            NSDictionary *addressDic = placemark.addressDictionary;
            
            NSString *city = [addressDic  objectForKey:@"City"];
            
            NSLog(@"city %@",city);
        }
        
    }];
    
    [self.myLocationManager stopUpdatingHeading];
    
}

-(void)getAddressByLatitude:(CLLocationDegrees)latitude longitude:(CLLocationDegrees)longitude{
    //反地理编码
    CLLocation *location=[[CLLocation alloc]initWithLatitude:latitude longitude:longitude];
    
    [self.myGeocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
        
        for(CLPlacemark *placemark in placemarks){
        
            NSDictionary *addressDic = placemark.addressDictionary;
            
            NSString *city = [addressDic objectForKey:@"City"];
            
            NSLog(@"%@",city);
        }
        
    }];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
    NSLog(@"%@",error);
    
}



-(void)viewWillLayoutSubviews{
    
    [_myWeatherView myFontSetter];
    
}


- (void)startTimer{
    
    _myTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(myScroll) userInfo:NULL repeats:YES];
    
    [[NSRunLoop mainRunLoop]addTimer:_myTimer forMode:NSRunLoopCommonModes];
    
}

- (void)stopTimer{
    
    [_myTimer invalidate];
    
    _myTimer = nil;
}

- (void)myScroll{
    
    NSIndexPath *currentIndexPath = [[_myLooper indexPathsForVisibleItems]lastObject];
    
    if (currentIndexPath.item <2) {
        
        [_myLooper scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:currentIndexPath.item + 1 inSection:1] atScrollPosition:0 animated:YES];
    }
    
    if (currentIndexPath.item == 2) {
        
        [_myLooper scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:2] atScrollPosition:0 animated:YES];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
             [_myLooper scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:1] atScrollPosition:0 animated:NO];
            
        });
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    
    [self scrollViewDidEndDecelerating:scrollView];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self stopTimer];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    [self startTimer];
}

- (NSArray *)cellImageArray{
    
    NSArray *imageArray = @[
                            @"http://img.guahao.com/portal_upload/rollingnews/1453447883150.jpg",
                            @"http://img.guahao.com/portal_upload/mediafocus/1461826474435.jpg",
                            @"http://img.guahao.com/portal_upload/rollingnews/1461574027543.jpg"
                            ];
    if (!_cellImageArray) {
        
        _cellImageArray = [NSArray arrayWithArray:imageArray];
    }
    
    return _cellImageArray;
}

- (void)addMyWeather{
    
    self.navigationController.navigationBar.translucent = NO;
    
    _myWeatherView = [[MyWeatherView alloc]init];
    
    [self.view addSubview:_myWeatherView];
    
    _myWeatherView.userInteractionEnabled = YES;
    
    [_myWeatherView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.leading.top.trailing.equalTo(self.view);
        
        make.height.equalTo(screenH / 8);
        
    }];
    
   
    __weak HomeViewController *weakSelf = self;
    
    _myWeatherView.weatherBlock = ^(ProvinceController *myProvinceController){
        
        [weakSelf.navigationController pushViewController:(UIViewController *)myProvinceController animated:YES];
        
    };
    
}


//轮播器
- (void)addMyLooper{
    
    UICollectionViewFlowLayout *myLooperLayout = [[UICollectionViewFlowLayout alloc]init];
    
    _myLooper = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 100, 100, 100) collectionViewLayout:myLooperLayout];
    
    [_myLooper registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:reuseID];
    
    [self.view addSubview:_myLooper];
    
    [_myLooper makeConstraints:^(MASConstraintMaker *make) {
       
        make.top.equalTo(_myWeatherView.mas_bottom);
        
        make.leading.trailing.equalTo(self.view);
        
        make.height.equalTo(screenH / 4);
        
    }];
    
    _myLooper.dataSource = self;
    
    _myLooper.delegate = self;
    
    myLooperLayout.itemSize = CGSizeMake(screenW, 200);
    
    myLooperLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    _myLooper.pagingEnabled = YES;
    
    _myLooper.bounces = NO;
    
    _myLooper.showsHorizontalScrollIndicator = NO;
    
    myLooperLayout.minimumLineSpacing = 0;
    
    myLooperLayout.minimumInteritemSpacing = 0;
    
    //添加pageView
    _myPageControl = [[UIPageControl alloc]init];
    
    [self.view addSubview:_myPageControl];
    
    [_myPageControl makeConstraints:^(MASConstraintMaker *make) {
       
        make.centerX.equalTo(_myLooper);
        
        make.centerY.equalTo(_myLooper.bottom).offset(-10);
        
    }];
    
    _myPageControl.numberOfPages = self.cellImageArray.count;
    
    _myPageControl.pageIndicatorTintColor = [UIColor grayColor];
    
    _myPageControl.currentPageIndicatorTintColor = [UIColor whiteColor];
    
}

- (void)viewDidLayoutSubviews{
    
    [_myLooper scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:1] atScrollPosition:UICollectionViewScrollPositionNone animated:NO];
}

#pragma mark ---collection delegate---

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 3;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.cellImageArray.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
   
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseID forIndexPath:indexPath];
    
    UIImageView *cellBackImageView = [[UIImageView alloc]init];
    
    [cellBackImageView sd_setImageWithURL:[NSURL URLWithString:self.cellImageArray[indexPath.item]] placeholderImage:[UIImage imageNamed:@"looperBg"]];
    
    cell.backgroundView = cellBackImageView;
    
    return cell;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    [_myLooper scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:(int)(scrollView.contentOffset.x / screenW) % self.cellImageArray.count  inSection:1] atScrollPosition:0 animated:NO];
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    NSInteger index = (scrollView.contentOffset.x - 3 * screenW) / screenW;
    
    _myPageControl.currentPage = index;

}

- (void)setupUI {
    
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.navigationBar.barTintColor = kThemeColor;
    
    self.title = @"黑马快医";
}

#pragma mark - 添加疾病类型的视图View
//view的高度是界面高度的0.6倍
-(void)addDiseaseTypeView{
    
    DiseaseTypeView *diseaseTypeview = [[DiseaseTypeView alloc] init];
    
    [self.view addSubview:diseaseTypeview];
    
    [diseaseTypeview mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(self.myLooper.mas_bottom);
        
        make.leading.trailing.bottom.equalTo(self.view);
        
    }];
}

@end
